/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;

import com.koron.report.bean.DangerAnalysis;
import com.koron.report.bean.riskanddanger.HiddenDangerDiscoveryDto;
import com.koron.report.mapper.statistics.HiddenDangerDiscoveryStatisticMapper;
import com.koron.report.service.api.DangerAnalysisService;
import com.koron.report.service.api.HiddenDangerDiscoveryAnalysisService;
import com.koron.report.util.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.system.domain.DictData;

import com.koron.system.service.api.DictDataService;
import com.koron.system.service.api.DistrictService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HiddenDangerDiscoveryAnalysisServiceImpl implements HiddenDangerDiscoveryAnalysisService {

    private final static  Logger logger= LoggerFactory.getLogger(HiddenDangerDiscoveryAnalysisServiceImpl.class);

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    @Autowired
    private DictDataService dataService;
    @Autowired
    private IndicationItemsService indicationItemsService;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private Util util;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private DangerAnalysisService dangerAnalysisService;
    @Override
    public MessageBean<DataBean<HiddenDangerDiscoveryDto>> hiddenDangerDiscoveryList(Integer type, String orgCode, Date updateTimeStart, Date updateTimeEnd, Integer start, Integer rows) {
        MessageBean<DataBean<HiddenDangerDiscoveryDto>> msg=new MessageBean<>();
        try(SessionFactory factory=new SessionFactory()) {
            List<String> corpCodeList=new ArrayList<>();
            List<String> gridCodeList=new ArrayList<>();
            switch (type){
                case 0:
                    //集团,返回所有隐患数据
                    corpCodeList=null;
                    gridCodeList=null;
                    break;
                case 1:
                    //具体某个水司
                    corpCodeList.add(orgCode);
                    gridCodeList=null;
                    break;
                case 2:
                    //具体某个水司,但旗下还有子公司
                    corpCodeList.add(orgCode);
                    List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree(orgCode,1).getData();
                    if (null!=departmentTreeBeanList&&departmentTreeBeanList.size()>0){
                        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
                        List<String> realCorpCodeList=new ArrayList<>();
                        if (null!=corpBeanList)
                            realCorpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
                        for(DepartmentTreeBean departmentTreeBean:departmentTreeBeanList){
                            if (realCorpCodeList.contains(departmentTreeBean.getDepartmentCode()))
                                corpCodeList.add(departmentTreeBean.getDepartmentCode());
                        }
                    }
                    break;
                case 3:
                    //具体某个网格
                    //判断点击的某个网格是否是水司
                    List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
                    List<String> realCorpCodeList=new ArrayList<>();
                    if (null!=corpBeanList)
                        realCorpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
                    if (realCorpCodeList.contains(orgCode))
                        corpCodeList.add(orgCode);
                    if (null==corpBeanList||corpBeanList.size()>0)
                        corpCodeList=null;
                    gridCodeList.add(orgCode);
                    break;
                default:
                    break;
            }
            HiddenDangerDiscoveryStatisticMapper mapper=factory.getMapper(HiddenDangerDiscoveryStatisticMapper.class);
            DataBean<HiddenDangerDiscoveryDto> dataBean=new DataBean<>();
            List<HiddenDangerDiscoveryDto> list=mapper.queryDangerListByCondition(corpCodeList,
                    gridCodeList,updateTimeStart,updateTimeEnd,start,rows);
            Integer totalNumber=mapper.countDangerListByCondition(corpCodeList,gridCodeList,updateTimeStart,updateTimeEnd);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            list.forEach(item->getNames(item));
            dataBean.setList(list);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(dataBean);
            return msg;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<DangerAnalysis>> getDangerAnalysisListByLevel(Integer orgLevel, String orgCode, Date startTime, Date endTime, Integer page, Integer pageSize) {
        MessageBean<DataBean<DangerAnalysis>> msg=new MessageBean<>();
        Map<String,String> map=dangerAnalysisService.getAnalysisDateMap();
        try (SessionFactory factory=new SessionFactory()){
            List<DangerAnalysis> analysisList=new ArrayList<>();
            switch (orgLevel){
                case 0:
                    //集团，返回所以已开通水司的数据
                    List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
                    if (null!=corpBeanList&&corpBeanList.size()>0){
                        for(CorpBean corpBean:corpBeanList){
                            List<String> corpCodeList=new ArrayList<>();
                            corpCodeList.add(corpBean.getCorpCode());
                            DangerAnalysis dangerAnalysis1=factory.getMapper(HiddenDangerDiscoveryStatisticMapper.class).queryDangerAnalysisList(map.get("nomarlDangerCount"),map.get("importantDangerCont"),map.get("managerDangetCount"),
                                    map.get("deviceDangerCount"),map.get("meterialDangerCount"),map.get("personDangerCount"),map.get("goodsDangerCount"),
                                    map.get("enviropmentDangerCount"),startTime,endTime,corpCodeList,null);
                            DangerAnalysis dangerAnalysis2=factory.getMapper(HiddenDangerDiscoveryStatisticMapper.class).queryDangerPrecautionAnalysisList(map.get("unreformCount"),map.get("alreadyReformCount1"),map.get("reformingCount"),
                                    map.get("alreadyReformCount1"),map.get("refuseReformCount"),startTime,endTime,corpCodeList,null);
                            if (null==dangerAnalysis1){
                                dangerAnalysis1=new DangerAnalysis();
                            }
                            dangerAnalysis1.setDepartmentCode(corpBean.getCorpCode());
                            dangerAnalysis1.setDepartmentName(corpBean.getCorpName());
                            if(null!=dangerAnalysis2){
                                computeRate(dangerAnalysis1,dangerAnalysis2);
                            }
                            analysisList.add(dangerAnalysis1);
                        }
                    }
                    break;
                case 1:
                    //水司
                    CorpBean corpBean=corpManagementService.getOne(orgCode).getData();
                    if (null!=corpBean){
                        List<DangerAnalysis> dangerAnalysisList2=factory.getMapper(HiddenDangerDiscoveryStatisticMapper.class).queryDangerAnalysisListLevelCorp(map.get("nomarlDangerCount"),map.get("importantDangerCont"),map.get("managerDangetCount"),
                                map.get("deviceDangerCount"),map.get("meterialDangerCount"),map.get("personDangerCount"),map.get("goodsDangerCount"),
                                map.get("enviropmentDangerCount"),startTime,endTime,orgCode);
                        for(DangerAnalysis dangerAnalysis:dangerAnalysisList2){
                            List<String> gridCodeList=new ArrayList<>();
                            gridCodeList.add(dangerAnalysis.getDepartmentCode());
                            DangerAnalysis dangerAnalysis7=factory.getMapper(HiddenDangerDiscoveryStatisticMapper.class).queryDangerPrecautionAnalysisList(map.get("unreformCount"),map.get("alreadyReformCount1"),map.get("reformingCount"),
                                    map.get("alreadyReformCount1"),map.get("refuseReformCount"),startTime,endTime,null,gridCodeList);
                            if(null!=dangerAnalysis7){
                                computeRate(dangerAnalysis,dangerAnalysis7);
                            }
                            analysisList.add(dangerAnalysis);
                        }
                    }
                default:
                    break;
            }
            if(analysisList!=null&&analysisList.size()>0){
                Integer totalNumber=analysisList.size();
                pageSize=pageSize==null||pageSize<=0?totalNumber:pageSize;
                Integer start=0,end=15,totalPage=1;
                if(page!=null&&page>1){
                    if(pageSize==null||pageSize<=0){
                        pageSize=15;
                    }
                    start=(page-1)*pageSize;
                    end=start+pageSize;
                }
                if (end>totalNumber){
                    end=totalNumber;
                    if (start>end){
                        start=end;
                    }
                    totalPage = totalNumber / pageSize + 1;
                }
                DataBean<DangerAnalysis> dataBean=new DataBean<>();
                dataBean.setPageSize(pageSize);
                dataBean.setPageNo(page);
                dataBean.setTotalPage(totalPage);
                dataBean.setTotalNumber(totalNumber);
                dataBean.setList(analysisList.subList(start,end));
                msg.setData(dataBean);
            }else{
                msg.setData(null);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            return msg;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public Integer checkLevel(String orgCode) {
        //集团编码
        if(StringUtils.isEmpty(orgCode)||orgCode.equals("776B361BFFAC4F00BBF459CD1303A8B2")){
            return 0;
        }
        //查询所有已开通水司
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
        //水司code集合
        List<String> corpCode=new ArrayList<>();
        if (null!=corpBeanList&&corpBeanList.size()>0){
            corpCode=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
        }
        if(corpCode.contains(orgCode)){
            return  1;
        }else{
            //非集团、水司、全部默认为网格
            return 2;
        }
    }

    private void computeRate(DangerAnalysis target,DangerAnalysis source){
        target.setAlreadyReformCount(source.getAlreadyReformCount());
        target.setReformingCount(source.getReformingCount());
        target.setUnreformCount(source.getUnreformCount());
        //计算整改率
        Integer total=source.getUnreformCount()+source.getReformingCount()+source.getAlreadyReformCount();
        BigDecimal totalValue=new BigDecimal(total);
        BigDecimal rate=total==0?new BigDecimal(0):new BigDecimal(source.getAlreadyReformCount()).divide(totalValue,4,BigDecimal.ROUND_HALF_UP);
        target.setReformRate(rate);
    }

    private void setNames(HiddenDangerDiscoveryDto danger) {
        if (danger != null) {
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            Map<String, IndicationItems> cache = indicationItemsService.getCacheMap();
            if (StringUtils.isNotBlank(danger.getElementFristType())) {
                DictData element = cacheMap.get(danger.getElementFristType());
                danger.setElementFristTypeName(element != null ? element.getDictLabel() : "");
            }
            if (StringUtils.isNotBlank(danger.getElementSecondType())) {
                DictData element = cacheMap.get(danger.getElementSecondType());
                danger.setElementSecondTypeName(element != null ? element.getDictLabel() : "");
            }
            if (StringUtils.isNotBlank(danger.getDangerType())) {
                IndicationItems indication = cache.get(danger.getDangerType());
                danger.setDangerTypeName(indication != null ? indication.getName() : "");
            }
            if (StringUtils.isNotBlank(danger.getDangerLevel())) {
                IndicationItems indication = cache.get(danger.getDangerLevel());
                danger.setDangerLevelName(indication != null ? indication.getName() : "");
            }
            SessionFactory factory=new SessionFactory();
            if(StringUtils.isNotEmpty(danger.getCorpCode())){
                CorpBean corpBean=factory.getMapper(CorpManagementMapper.class).get(danger.getCorpCode());
                danger.setCorpName(corpBean==null?null:corpBean.getCorpName());
            }
            List<HiddenDangerRectification> rectificationList=factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(danger.getId());
            if (null!=rectificationList&&rectificationList.size()>0){
                danger.setRectifier(rectificationList.get(0).getRectifier());
                danger.setDeadline(rectificationList.get(0).getDeadline());
                danger.setRectifierName(rectificationList.get(0).getRectifierName());
                danger.setRectificationResult(rectificationList.get(0).getRectificationResult());
                danger.setReviewerName(rectificationList.get(0).getReviewerName());
                danger.setReviewer(rectificationList.get(0).getReviewer());
                danger.setSolution(rectificationList.get(0).getSolution());
                danger.setReviewTime(rectificationList.get(0).getReviewTime());
                danger.setReviewResult(rectificationList.get(0).getReviewResult());
                danger.setConfirmPerson(rectificationList.get(0).getConfirmPerson());
                danger.setConfirmPersonName(rectificationList.get(0).getConfirmPersonName());
                if (StringUtils.isNotEmpty(rectificationList.get(0).getRectificationState())){
                    IndicationItems indication = cache.get(rectificationList.get(0).getRectificationState());
                    danger.setDangerRectificationStateName(indication != null ? indication.getName() : "");
                }
            }
            factory.close();
        }
    }
    private void getNames(HiddenDangerDiscoveryDto bean){
        if (null != bean) {
            setNames(bean);
            //bean.setGroupName("粤海水资源");
            Port port=getPort();
            if (StringUtils.isNotEmpty(bean.getInnerStaff())) {
                List<String> origin = JSONObject.parseArray(bean.getInnerStaff(), String.class);
                List<String> names = new ArrayList<>();
                for (String innerStaff : origin) {
                    String staffCode = innerStaff.split("_")[0];
                    List<DeptBean> departmentTreeBeanList = port.dept(staffCode).getData();
                    List<StaffBean> staffBeanList = port.staff(staffCode, null).getData();
                    if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 0 && null != staffBeanList && staffBeanList.size() > 0) {
                        names.add(staffBeanList.get(0).getName() + "_" + departmentTreeBeanList.get(0).getName());
                    }
                }
                bean.setInnerStaffName(new Gson().toJson(names));
            }
        }
    }
    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appid);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }
}
